package top.continew.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.continew.admin.system.mapper.ExportTaskMapper;
import top.continew.admin.system.model.entity.ExportTaskDO;
import top.continew.admin.system.model.resp.ExportTaskResp;
import top.continew.admin.system.service.ExportTaskService;
import top.continew.starter.data.mp.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 导出任务服务实现
 */
@Service
@RequiredArgsConstructor
public class ExportTaskServiceImpl extends ServiceImpl<ExportTaskMapper, ExportTaskDO> implements ExportTaskService {

    @Override
    public String createTask(String taskName, Long userId) {
        String taskId = UUID.randomUUID().toString();
        ExportTaskDO task = new ExportTaskDO();
        task.setTaskId(taskId);
        task.setTaskName(taskName);
        task.setStatus("PENDING");
        task.setProgress(0);
        task.setCreateUser(userId);
        task.setUpdateUser(userId);
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        this.save(task);
        return taskId;
    }

    @Override
    public void updateTaskStatus(String taskId, String status, Integer progress, String errorMessage) {
        ExportTaskDO task = new ExportTaskDO();
        task.setStatus(status);
        task.setProgress(progress);
        task.setErrorMessage(errorMessage);
        task.setUpdateTime(LocalDateTime.now());
        this.update(task, new LambdaQueryWrapper<ExportTaskDO>().eq(ExportTaskDO::getTaskId, taskId));
    }

    @Override
    public void completeTask(String taskId, String filePath, String fileName) {
        ExportTaskDO task = new ExportTaskDO();
        task.setStatus("COMPLETED");
        task.setProgress(100);
        task.setFilePath(filePath);
        task.setFileName(fileName);
        task.setCompleteTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        this.update(task, new LambdaQueryWrapper<ExportTaskDO>().eq(ExportTaskDO::getTaskId, taskId));
    }

    @Override
    public List<ExportTaskResp> getUserTasks(Long userId) {
        List<ExportTaskDO> tasks = this.list(
            new LambdaQueryWrapper<ExportTaskDO>()
                .eq(ExportTaskDO::getCreateUser, userId)
                .orderByDesc(ExportTaskDO::getCreateTime)
        );
        return tasks.stream().map(this::convertToResp).collect(Collectors.toList());
    }

    @Override
    public ExportTaskResp getTaskDetail(String taskId) {
        ExportTaskDO task = this.getOne(new LambdaQueryWrapper<ExportTaskDO>().eq(ExportTaskDO::getTaskId, taskId));
        return task != null ? convertToResp(task) : null;
    }

    @Override
    public PageResp<ExportTaskResp> getUserTasksPage(Long userId, PageQuery pageQuery) {
        Page<ExportTaskDO> page = new Page<>(pageQuery.getPage(), pageQuery.getSize());
        Page<ExportTaskDO> result = this.page(page, 
            new LambdaQueryWrapper<ExportTaskDO>()
                .eq(ExportTaskDO::getCreateUser, userId)
                .orderByDesc(ExportTaskDO::getCreateTime)
        );
        
        // 转换为响应对象
        Page<ExportTaskResp> respPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        List<ExportTaskResp> records = result.getRecords().stream()
            .map(this::convertToResp)
            .collect(Collectors.toList());
        respPage.setRecords(records);
            
        return PageResp.build(respPage);
    }

    @Override
    public void downloadFile(String taskId, HttpServletResponse response) {
        try {
            ExportTaskDO task = this.getOne(new LambdaQueryWrapper<ExportTaskDO>().eq(ExportTaskDO::getTaskId, taskId));if (task == null || !"COMPLETED".equals(task.getStatus()) || StrUtil.isBlank(task.getFilePath())) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            response.sendRedirect(task.getFilePath());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private ExportTaskResp convertToResp(ExportTaskDO task) {
        ExportTaskResp resp = new ExportTaskResp();
        BeanUtils.copyProperties(task, resp);
        return resp;
    }
}